package com.soft.sitegenerator.business.hibernate;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.soft.sitegenerator.Component;
import com.soft.sitegenerator.DataBaseComponent;
import com.soft.sitegenerator.exceptions.ObjectNotFoundException;

public class CompositeTemplate extends Template {

	private Long id;

	private String description;

	private Set templates = new HashSet();

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Set getTemplates() {
		return templates;
	}

	public void setTemplates(Set templates) {
		this.templates = templates;
	}

	public void delete() {
		try {
			this.load();
			hibernateDAOHib.delete(this);
		} catch (ObjectNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void clonar() {
		Component component = new DataBaseComponent();
		for (Iterator i = this.templates.iterator(); i.hasNext();) {
			Template template = (Template) i.next();
			if (template.getHibernateDAOHib()==null) {
				Template templateHib = null;
				if (template instanceof SimpleTemplate) {
					templateHib = (SimpleTemplate) component.getBean("simpleTemplatesHib");
				} else {
					templateHib = (CompositeTemplate) component.getBean("compositeTemplatesHib");
				}
				
				templateHib.setId(template.getId());
				try {
					templateHib.load();
					template=templateHib;
				} catch (ObjectNotFoundException e) {
					e.printStackTrace();
				}
			} 
			template.clonar();
		}
		hibernateDAOHib.save(this);
		try {
			load();
			for (Iterator i = this.templates.iterator(); i.hasNext();) {
				Template template = (Template) i.next();
				if (template.getHibernateDAOHib()==null) {
					Template templateHib = null;
					if (template instanceof SimpleTemplate) {
						templateHib = (SimpleTemplate) component.getBean("simpleTemplatesHib");
					} else {
						templateHib = (CompositeTemplate) component.getBean("compositeTemplatesHib");
					}
					
					templateHib.setId(template.getId());
					try {
						templateHib.load();
						template=templateHib;
					} catch (ObjectNotFoundException e) {
						e.printStackTrace();
					}
				} 
				template.setCanUpdate(this.getCanUpdate());
				template.update();
			}
		} catch (ObjectNotFoundException e1) {
			e1.printStackTrace();
		}
	}

	public Collection findAll() {
		return hibernateDAOHib.find("from CompositeTemplate order by name");
	}

	public Collection findAllNotModificable() {
		return hibernateDAOHib.find("from CompositeTemplate where canUpdate = 'no' order by name");
	}

}
